package org.hackystat.ambientdevice.xml;

import java.io.File;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.hackystat.ambientdevice.server.jaxb.Configuration;
import org.hackystat.ambientdevice.server.jaxb.Project;
import org.xml.sax.SAXException;

/**
 * Again no comments by shao xuan.
 * 
 * @author shao xuan
 */
public class ConfigurationLoader {
  
  private JAXBContext configurationJaxbContext;
  private Configuration configuration;
  
  /**
   * The configuration Loader.
   * 
   * @param configFilePath the file path for the config loader
   * @throws Exception for errors
   */
  public ConfigurationLoader(String configFilePath) throws Exception {
    String jaxbContentString = "org.hackystat.ambientdevice.server.jaxb";
    this.configurationJaxbContext = JAXBContext.newInstance(jaxbContentString);
    File configFile = new File(configFilePath);
    Unmarshaller unmarshaller = configurationJaxbContext.createUnmarshaller();
    
  //Add schema check.
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    String schemaPath = System.getProperty("user.dir") + "/xml/schema/configuration.xsd";
    File schemaFile = new File(schemaPath.replace("/", System.getProperty("file.separator")));
    Schema schema = null;
    try {
      schema = schemaFactory.newSchema(schemaFile);
    }
    catch (SAXException e) {
      e.printStackTrace();
    }
    unmarshaller.setSchema(schema);
    //Unmarshal
    this.configuration = (Configuration) unmarshaller.unmarshal(configFile);
  }
  
  /**
   * @return Configuration file that has been loaded.
   */
  public Configuration getConfiguration () {
    return this.configuration;
  }
  
  /**
   * gets the projects.
   * @return a list of projects. 
   */
  public List<Project> getProjects () {
    return this.configuration.getProjects().getProject();
  }

}
